Repository navigation
Fix CancellableQueue retaining tasks that finish before registration - #81
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #81 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 13 13
Lines 1297 1313 +16
=========================================
+ Hits 1297 1313 +16
🚀 New features to boost your workflow:
|
dfed
left a comment
There was a problem hiding this comment.
Great find!
Two things before this can merge, both detailed inline with suggestions:
- The fix introduces a new race.
cancelTasks()removes reservations, so a task enqueued whilecancelTasks()is running can end up permanently uncancellable. - The new tests are probabilistic. I'd like them to be deterministic like the rest of the suite, and I've suggested one way to get there. If you see a different way to force the ordering, I'm open to it.
I ran the suggested changes locally and the full suite passes with them.
| $0.removeAll() | ||
| } | ||
| } |
There was a problem hiding this comment.
removeAll() also removes the nil reservations. If cancelTasks() runs on another thread between a task's reservation and its registration, the registration is skipped because the key is gone. That task is still running but is now untracked, so no later cancelTasks() can cancel it. On main the same task would be registered late and cancelled by the next call.
Keeping the reservations fixes it. This suggestion also moves the bookkeeping into three internal methods so the tests can drive the ordering deterministically (see my comments on the tests).
| $0.removeAll() | |
| } | |
| } | |
| // Keep reservations so that tasks that have not yet registered remain cancellable. | |
| $0 = $0.filter { $0.value == nil } | |
| } | |
| } | |
| // MARK: Internal | |
| /// Reserves an identifier for a task that is about to be created. | |
| /// Reserving before the task starts ensures the task's removal of the identifier can never be processed before the reservation. | |
| func reserveTaskIdentifier() -> UUID { | |
| let identifier = UUID() | |
| taskIdentifierToCancelMap.writeAsync { | |
| $0.updateValue(nil, forKey: identifier) | |
| } | |
| return identifier | |
| } | |
| /// Registers the `cancel` closure for a task whose identifier was previously reserved. | |
| func registerCancellation(forTaskWithIdentifier identifier: UUID, _ cancel: @escaping @Sendable () -> Void) { | |
| taskIdentifierToCancelMap.writeAsync { | |
| // Skip registration if the identifier was already removed because the task already finished. | |
| if $0.keys.contains(identifier) { | |
| $0[identifier] = cancel | |
| } | |
| } | |
| } | |
| /// Removes the identifier of a task that has finished executing. | |
| func taskDidFinish(withIdentifier identifier: UUID) { | |
| taskIdentifierToCancelMap.writeAsync { | |
| $0[identifier] = nil | |
| } | |
| } |
| let identifier = UUID() | ||
| // Reserve the identifier before the task starts so that the task's removal of the identifier | ||
| // can never be processed before the task's registration below. | ||
| actorQueue.taskIdentifierToCancelMap.writeAsync { | ||
| $0.updateValue(nil, forKey: identifier) | ||
| } |
There was a problem hiding this comment.
With the helpers above, this becomes one line. Could you apply the same change to the other seven initializers?
| let identifier = UUID() | |
| // Reserve the identifier before the task starts so that the task's removal of the identifier | |
| // can never be processed before the task's registration below. | |
| actorQueue.taskIdentifierToCancelMap.writeAsync { | |
| $0.updateValue(nil, forKey: identifier) | |
| } | |
| let identifier = actorQueue.reserveTaskIdentifier() |
The defer body just below would then become actorQueue.taskDidFinish(withIdentifier: identifier).
| actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in | ||
| $0[identifier] = cancel | ||
| // Skip registration if the identifier was already removed, e.g. because the task already finished. | ||
| if $0.keys.contains(identifier) { | ||
| $0[identifier] = cancel | ||
| } | ||
| } |
There was a problem hiding this comment.
Same here, and in the other seven initializers.
| actorQueue.taskIdentifierToCancelMap.writeAsync { [cancel] in | |
| $0[identifier] = cancel | |
| // Skip registration if the identifier was already removed, e.g. because the task already finished. | |
| if $0.keys.contains(identifier) { | |
| $0[identifier] = cancel | |
| } | |
| } | |
| actorQueue.registerCancellation(forTaskWithIdentifier: identifier, cancel) |
| @Test | ||
| func cancelTasks_actorQueue_doesNotCancelManyCompletedTasks() async { | ||
| let actorQueue = ActorQueue<Counter>() | ||
| let counter = Counter() | ||
| actorQueue.adoptExecutionContext(of: counter) | ||
| let systemUnderTest = CancellableQueue(underlyingQueue: actorQueue) | ||
|
|
||
| // Create and complete many tasks. A task can finish before it is registered with the queue, | ||
| // so use enough tasks to reliably exercise that ordering. | ||
| var tasks = [Task<Void, any Error>]() | ||
| for _ in 0..<1_000 { | ||
| let task = Task(on: systemUnderTest) { _ in | ||
| try doWork() | ||
| } | ||
| _ = await task.result | ||
| tasks.append(task) | ||
| } | ||
|
|
||
| // Now cancel tasks - should have no effect since every task already completed. | ||
| systemUnderTest.cancelTasks() | ||
|
|
||
| #expect(tasks.allSatisfy { !$0.isCancelled }) | ||
| } | ||
|
|
There was a problem hiding this comment.
The two deterministic tests above cover the bookkeeping for both queue types, so this one can go.
| @Test | |
| func cancelTasks_actorQueue_doesNotCancelManyCompletedTasks() async { | |
| let actorQueue = ActorQueue<Counter>() | |
| let counter = Counter() | |
| actorQueue.adoptExecutionContext(of: counter) | |
| let systemUnderTest = CancellableQueue(underlyingQueue: actorQueue) | |
| // Create and complete many tasks. A task can finish before it is registered with the queue, | |
| // so use enough tasks to reliably exercise that ordering. | |
| var tasks = [Task<Void, any Error>]() | |
| for _ in 0..<1_000 { | |
| let task = Task(on: systemUnderTest) { _ in | |
| try doWork() | |
| } | |
| _ = await task.result | |
| tasks.append(task) | |
| } | |
| // Now cancel tasks - should have no effect since every task already completed. | |
| systemUnderTest.cancelTasks() | |
| #expect(tasks.allSatisfy { !$0.isCancelled }) | |
| } |
|
Thanks, good catch on the removeAll() race. Applied your suggestions across all eight initializers and swapped the probabilistic tests for your two deterministic ones. I also checked that the first fails without the reservation check and the second fails with removeAll() restored. |
A task enqueued on a CancellableQueue can finish before its cancel handle is registered. When that happens, its removal from the map is processed before the registration, so the entry is never removed. The task and its result stay alive, and a later
cancelTasks()cancels already-completed tasks. This reserves the identifier before the task starts and skips registration if the identifier is already gone.The new tests complete 1000 tasks and then call
cancelTasks(). They failed every run on Linux (swift:6.2) before this change and pass consistently after it. Not tested on Apple platforms.